<template>
    <div class="admin-promotional">
        <div class="admin-promotional-header">更新活动</div>
        <div class="admin-promotional-content">
            <el-form :model="promotionalData" label-width="auto" style="max-width: 1000px">
                <div style="width: 276px;">
                    <el-form-item label="标题（中文）">
                        <el-input v-model="promotionalData.title" />
                    </el-form-item>
                </div>
                <div style="width: 276px;">
                    <el-form-item label="标题（英文）">
                        <el-input v-model="promotionalData.title_en" />
                    </el-form-item>
                </div>
                <!-- 封面 -->
                <div style="margin-bottom: 10px; font-size: 13px;">
                    <span>封面</span>
                </div>
                <div
                    style="display: flex; justify-content: center; border: 1px solid #eee; height: 200px; width: 820px; text-align: center;">
                    <div style="width: 400px;">
                        <div style="width: 400px; margin-bottom: 30px; margin-top: 10px">
                            <el-alert title="建议上传图片参考大小： 750px * 375px" type="warning" show-icon :closable="false" />
                        </div>
                        <el-upload class="avatar-uploader" :action="uploadUrl"
                            :show-file-list="false" :headers="headersAdmin" :on-success="handleProductCoverSuccess"
                            style="width: 400px;">
                            <img v-if="promotionalData.cover"
                                :src="promotionalData.cover + '?x-oss-process=image/resize,h_100/quality,q_50'"
                                class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </div>
                </div>
                <!-- 富文本编辑器 -->
                <div style="margin-bottom: 10px; font-size: 13px; margin-top: 30px;">
                    <span>内容（中文）</span>
                </div>
                <div style="border: 1px solid #ccc">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                        :mode="mode" />
                    <Editor style="height: 600px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
                        :mode="mode" @onCreated="handleCreated" />
                </div>
                <!-- 英文编辑器 -->
                <div style="margin-bottom: 10px; font-size: 13px; margin-top: 30px;">
                    <span>内容（英文）</span>
                </div>
                <div style="border: 1px solid #ccc">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRefEn" :defaultConfig="toolbarConfigEn"
                        :mode="mode" />
                    <Editor style="height: 600px; overflow-y: hidden;" v-model="valueHtmlEn" :defaultConfig="editorConfigEn"
                        :mode="mode" @onCreated="handleCreatedEn" />
                </div>
            </el-form>
            <div style="text-align: center; margin-top: 20px;">
                <el-button type="primary" @click="onSubmitAddPromotional">更新</el-button>
                <el-button type="primary"  @click="goBack">返回</el-button>
            </div>
        </div>
    </div>

</template>

<script>
import '@wangeditor/editor/dist/css/style.css';
import { onBeforeUnmount, ref, shallowRef, reactive, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { addNews, delEditorImg,  getNews}  from '../../requests/index';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { uploadUrl, uploadEditUrl} from '../../utils/request';

export default {
    components: { Editor, Toolbar },
    setup() {
        const router = useRouter();
        
        const token = window.localStorage.getItem("token");
        const headersAdmin = {
            Authorization: `Bearer ${token}`
        };
        const promotionalData = reactive({
            id: "",
            title: "",
            title_en: "",
            cover: "",
            content: "",
            content_en: "",
            imgs: "",
            imgs_en: ""
        });
        const imgInsert = [];
        const imgInsertEn = [];
        const valueHtml = ref();
        const valueHtmlEn = ref();
        onMounted(async () =>{
            const route = useRoute();
            const params = route.query;
            const res = await getNews({"id": params.id});
            if (res.status === 2000){
                const data = res.data;
                promotionalData.id = data.id;
                promotionalData.title = data.title;
                promotionalData.title_en = data.title_en;
                promotionalData.cover = data.cover;
                promotionalData.content = data.content;
                promotionalData.content_en = data.content_en;
                valueHtml.value = data.content;
                valueHtmlEn.value = data.content_en;
            }
        });
        // 上传封面图片
        const handleProductCoverSuccess = async(response, uploadFilled) =>{
            if (response.status === 2000) {
                if (promotionalData.cover){
                    const res = await delOssImg({"img":promotionalData.cover});
                };
                promotionalData.cover = response.file;
            } else {
                ElMessage.error(response.msg);
            };
        };
        // 编辑器实例，必须用 shallowRef
        const editorRef = shallowRef();
        const toolbarConfig = {};
        const editorConfig = { MENU_CONF: {} };
        editorConfig.placeholder = "请输入...";
        editorConfig.MENU_CONF['uploadImage'] = {
            server: uploadEditUrl,
            headers: {
                Authorization: `Bearer ${token}`
            }
        };
        // 获取已经插入的图片
        editorConfig.MENU_CONF['insertImage'] = {
            onInsertedImage(imageNode) {
                if (imageNode == null) return
                const { src, alt, url, href } = imageNode;
                imgInsert.push(src);
            }
        };
        // 组件销毁时，也及时销毁编辑器
        onBeforeUnmount(() => {
            // 销毁中文
            const editor = editorRef.value
            if (editor == null) return
            editor.destroy();
            // 销毁英文
            const editorEn = editorRefEn.value
            if (editorEn == null) return
            editorEn.destroy()
        });

        const handleCreated = (editor) => {
            editorRef.value = editor // 记录 editor 实例，重要！
        };
        
        // 英文
        // 编辑器实例，必须用 shallowRef
        const editorRefEn = shallowRef();
        // 内容 HTML

        const toolbarConfigEn = {};
        const editorConfigEn = { MENU_CONF: {} };
        editorConfigEn.placeholder = "Please input...";
        editorConfigEn.MENU_CONF['uploadImage'] = {
            server: uploadEditUrl,
            headers: {
                Authorization: `Bearer ${token}`
            }
        };
        // 获取已经插入的图片
        editorConfig.MENU_CONF['insertImage'] = {
            onInsertedImage(imageNode) {
                if (imageNode == null) return
                const { src, alt, url, href } = imageNode;
                imgInsertEn.push(src);
            }
        };
        const handleCreatedEn = (editor) => {
            editorRefEn.value = editor; // 记录 editor 实例，重要！
        };

        // 提交促销活动
        const onSubmitAddPromotional = async()=>{
            promotionalData.content = valueHtml.value;
            promotionalData.content_en = valueHtmlEn.value;
            const imgFinal = editorRef.value.getElemsByType('image');
            const imgFinalEn = editorRefEn.value.getElemsByType('image');
            const imgFinalSrc = imgFinal.map(item => item.src);
            const imgFinalSrcEn = imgFinalEn.map(item => item.src);       
            promotionalData.imgs = imgFinalSrc.toString();
            promotionalData.imgs_en = imgFinalSrcEn.toString();                 
            const res = await addNews(promotionalData);
            if (res.status === 2000){
                // editor = editorRef.value
                const setResult = imgInsert.filter(item => !imgFinalSrc.includes(item));
                const setResultEn = imgInsertEn.filter(item => !imgFinalSrcEn.includes(item));
                // 把两边的图片合并在一起
                const setImgs = setResult.concat(setResultEn);
                if (setImgs.length > 0){
                    const res = await delEditorImg({"img": setResult.toString()});
                    console.log(res);
                }
                ElMessage.success("更新成功");
                router.push({ path: '/admin/news' });
            }else{
                ElMessage.error("更新失败");
            };
        };
        // 返回
        const goBack = ()=>{
            router.push({ path: '/admin/news' });
        };
        
        return {
            goBack,
            headersAdmin,
            promotionalData,
            editorRef,
            valueHtml,
            mode: 'default', // 或 'simple'
            toolbarConfig,
            editorConfig,
            uploadUrl,
            handleCreated,
            handleProductCoverSuccess,
            onSubmitAddPromotional,
            editorRefEn,
            toolbarConfigEn,
            valueHtmlEn,
            editorConfigEn,
            handleCreatedEn,
        };
    }
}
</script>
<style scoped>
.admin-promotional-header {
    margin-top: 20px;
    margin-left: 20px;
    height: 40px;
    line-height: 40px;
    background-color: #F9F9F9;
    padding-left: 20px;
    padding-right: 20px;
}

.admin-promotional-content {
    margin-top: 80px;
    margin-bottom: 50px;
    margin-left: 20px;
}

.admin-promotional {
    display: flex;
    min-height: 100px;
}
</style>